package com.jf.concurrent.lock;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import static java.lang.System.out;
import static java.lang.Thread.currentThread;

/**
 * TODO
 *
 * @author Junfeng
 */
public class ReadWriteLockDemo {

    public static void main(String[] arg) {


        for (int i = 0; i < 5; i++) {
            int finalI = i;
            new Thread(() -> {
                MyCache.getInstance().put(String.valueOf(finalI), finalI);
            }, "W" + i).start();
        }

        for (int i = 0; i < 5; i++) {
            int finalI = i;
            new Thread(() -> {
                MyCache.getInstance().get(String.valueOf(finalI));
            }, "R" + i).start();
        }

    }
}


class MyCache {

    private volatile Map<String, Object> CACHE = new HashMap<>();
    private ReadWriteLock lock = new ReentrantReadWriteLock();

    private static volatile MyCache INSTANCE;

    private MyCache() {
    }

    public static MyCache getInstance() {
        if (null == INSTANCE) {
            synchronized (MyCache.class) {
                if (null == INSTANCE) {
                    INSTANCE = new MyCache();
                }
            }
        }
        return INSTANCE;
    }

    public void put(String key, Object value) {
        lock.writeLock().lock();
        try {
            out.println(currentThread().getName() + "\t 写入缓存：" + key);
            TimeUnit.MILLISECONDS.sleep(300);
            CACHE.put(key, value);
            out.println(currentThread().getName() + "\t 写入完成");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.writeLock().unlock();
        }
    }

    public Object get(String key) {
        lock.readLock().lock();
        try {
            out.println(currentThread().getName() + "\t 开始读取");
            TimeUnit.MILLISECONDS.sleep(300);
            Object o = CACHE.get(key);
            out.println(currentThread().getName() + "\t 读取完成 + " + o);
            return o;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            lock.readLock().unlock();
        }
    }
}